package com.icefish.control;

import com.alibaba.fastjson.JSONObject;
import com.icefish.bean.User;
import com.icefish.bean.fastjsonParse.Meta;
import com.icefish.bean.fastjsonParse.createUser.CreateUserRsp;
import com.icefish.dao.UserDao;
import com.icefish.daoFactory.DaoFactory;
import com.icefish.utils.Init_Req_Resp_Config;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/CreateUser")
public class CreateUser extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Init_Req_Resp_Config.init(request, response);

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String user_picture = request.getParameter("user_picture");
        String type = request.getParameter("type");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setUser_picture(user_picture);
        user.setType(type);
        // 默认设置
        user.setLevel(1);
        user.setGrade("vip");
        user.setWallet(1000);
        user.setState_message("这个人很懒，什么都没有留下");


        Boolean isok = null;

        // 1、调用UserDao.insert方法，添加用户
        UserDao ud =  DaoFactory.getUserDaoInstance();

        try {
            isok  = ud.inserUser(user);
            Integer user_id = ud.selectByNamePWD(username,password);
            user = ud.selectByID(user_id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        CreateUserRsp cur = null;

        // 2、添加成功，返回数据
        if (isok) {
            Meta meta = new Meta("添加用户成功",201);
            cur = new CreateUserRsp(user,meta);
        }
        // 3、添加失败，返回数据
        else {
            User fakeUser = new User();
            Meta meta = new Meta("添加用户失败",200);
            cur = new CreateUserRsp(fakeUser,meta);
        }

        JSONObject jsonObject = new JSONObject();
        // 转换成json
        String backToBrowser = jsonObject.toJSONString(cur);

        // 响应数据
        response.getWriter().write(backToBrowser);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
